/**
 * Copyright 2011, Under-Ground Studio.
 *  
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *  
 *      http://www.apache.org/licenses/LICENSE-2.0
 *  
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.edu.zju.vlis.aus.util;

import java.util.List;

import android.app.Activity;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.Intent.ShortcutIconResource;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.ResolveInfo;
import android.database.Cursor;
import android.graphics.drawable.Drawable;
import android.net.Uri;

public class AppHelper {

	/**
	 * <uses-permission
	 * android:name="com.android.launcher.permission.INSTALL_SHORTCUT" />
	 * 
	 * @param context
	 * @param pkg
	 *            the package name of the target application to create
	 *            shortcut,not null
	 * @return true if create shortcut successfully,otherwise false.
	 */
	public static boolean createShortcut(Context context, String pkg) {
		// shortcut title
		String title = null;
		// MainActivity name
		String mainAct = null;
		// icon res id
		int iconId = 0;
		PackageManager pkgMag = context.getPackageManager();
		Intent queryIntent = new Intent(Intent.ACTION_MAIN, null);
		queryIntent.addCategory(Intent.CATEGORY_LAUNCHER);
		List<ResolveInfo> list = pkgMag.queryIntentActivities(queryIntent,
				PackageManager.GET_ACTIVITIES);
		for (int i = 0; i < list.size(); i++) {
			ResolveInfo info = list.get(i);
			if (info.activityInfo.packageName.equals(pkg)) {
				title = info.loadLabel(pkgMag).toString();
				mainAct = info.activityInfo.name;
				iconId = info.activityInfo.applicationInfo.icon;
				break;
			}
		}
		if (mainAct == null) {
			// no launch activity
			return false;
		}
		Intent shortcut = new Intent(
				"com.android.launcher.action.INSTALL_SHORTCUT");
		// 1.shortcut name
		shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME, title);
		// no duplicate
		shortcut.putExtra("duplicate", false);
		// 2.shortcut target intent
		ComponentName comp = new ComponentName(pkg, mainAct);
		shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, new Intent(
				Intent.ACTION_MAIN).setComponent(comp));
		// 3.shortcut icon
		Context pkgContext = null;
		if (context.getPackageName().equals(pkg)) {
			pkgContext = context;
		} else {
			try {
				pkgContext = context.createPackageContext(pkg,
						Context.CONTEXT_IGNORE_SECURITY
								| Context.CONTEXT_INCLUDE_CODE);
			} catch (NameNotFoundException e) {
				e.printStackTrace();
			}
		}
		if (pkgContext != null) {
			ShortcutIconResource iconRes = Intent.ShortcutIconResource
					.fromContext(pkgContext, iconId);
			shortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconRes);
		}

		// send broadcast
		context.sendBroadcast(shortcut);
		return true;

	}

	/**
	 * check whether the shortcut with the given name has been installed or not
	 * 
	 * @param context
	 * @param shortcutName
	 *            the name of the shortcut,generally it's the app name
	 * @return true if installed ,otherwise false.
	 */
	public static boolean isInstalledShortcut(Context context,
			String shortcutName) {
		boolean isInstallShortcut = false;
		final ContentResolver cr = context.getContentResolver();
		final String AUTHORITY = "com.android.launcher.settings";
		final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY
				+ "/favorites?notify=true");

		Cursor c = cr.query(CONTENT_URI,
				new String[] { "title", "iconResource" }, "title=?",
				new String[] { shortcutName }, null);// the name of the
														// app/shortcut
		if (c != null) {
			if (c.getCount() > 0) {
				isInstallShortcut = true;
			}
			c.close();
		}

		return isInstallShortcut;
	}

	/**
	 * uninstall the package with the given packageName
	 * 
	 * @param context
	 * @param packageName
	 *            the given package name
	 */
	public static void uninstallApp(Context context, String packageName) {
		Uri uri = Uri.fromParts("package", packageName, null);
		Intent intent = new Intent(Intent.ACTION_DELETE, uri);
		((Activity) context).startActivity(intent);
	}

	public static Drawable getAppIcon(Context context, String packageName) {
		PackageManager pm = context.getPackageManager();
		try {
			PackageInfo pInfo = pm.getPackageInfo(packageName, 0);
			return pInfo.applicationInfo.loadIcon(pm);
		} catch (NameNotFoundException ex) {
			return null;
		}
	}
	
	public static String getAppName(Context context,String packageName) {
		PackageManager pm = context.getPackageManager();
		String appName = "";
		try {
			PackageInfo pInfo = pm.getPackageInfo(packageName, 0);
			appName = (String) pInfo.applicationInfo.loadLabel(pm);
		} catch (NameNotFoundException e) {

		}
		return appName;
	}
	
	/**
	 * launch an application by its packeage name. 
	 * @param context
	 * @param packageName
	 */
	public static boolean launchApplication(Context context, String packageName) {
		PackageManager pm = context.getPackageManager();
		/*
		 * this code is trying to escape the exception when some times this list
		 * dose not get refreshed after application is uninstalled.
		 */
		try {
			Intent i = pm.getLaunchIntentForPackage(packageName);
			if (i != null) {
				context.startActivity(i);
			}
		} catch (Exception e) {
			return false;
		}
		return true;
	}
}
